package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    //获取购物车商品
    @Override
    public List<ShoppingCart> cartList(Long userId) {
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(lqw);
        return shoppingCarts;
    }

    //添加菜品到购物车
    @Override
    public ShoppingCart addCart(ShoppingCart shoppingCart) {
        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();
        Long userId = shoppingCart.getUserId();
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, dishId);
        lqw.eq(ShoppingCart::getUserId,userId);
        lqw.eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, setmealId);
        //查询购物车中是否存在该菜品存在 number+1
        ShoppingCart shoppingCart1 = shoppingCartMapper.selectOne(lqw);
        if (shoppingCart1 != null) {
            int number = shoppingCart1.getNumber() + 1;
            shoppingCart1.setNumber(number);
            shoppingCartMapper.updateById(shoppingCart1);
            return shoppingCart1;
        }
        shoppingCart.setNumber(1);
        shoppingCartMapper.insert(shoppingCart);
        return shoppingCart;
    }

    @Override
    public void clearCart(Long userId) {
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, userId);
        shoppingCartMapper.delete(lqw);
    }

    @Override
    public ShoppingCart updateCart(ShoppingCart shoppingCart) {
        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dishId != null, ShoppingCart::getDishId, dishId);
        lqw.eq(ShoppingCart::getUserId, shoppingCart.getUserId());
        lqw.eq(setmealId != null, ShoppingCart::getSetmealId, setmealId);
        ShoppingCart shoppingCart1 = shoppingCartMapper.selectOne(lqw);

        Integer number = shoppingCart1.getNumber();
        if (number == 1) {
            shoppingCart1.setNumber(0);
            shoppingCartMapper.delete(lqw);
            return shoppingCart1;
        }
        shoppingCart1.setNumber(number - 1);
        shoppingCartMapper.updateById(shoppingCart1);
        return shoppingCart1;
    }
}
